package com.guestbook.dao.impl;

import java.util.List;

import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.guestbook.dao.GuestBookDAO;
import com.guestbook.javabeans.GuestBook;
import com.tools.OraclePagination;
import com.tools.OracleUtil;
import com.tools.Pagination;

public class GuestBookDAOJdbc implements GuestBookDAO {
	private static final String SELECT_GUESTBOOKS_SQL = "select * from guestbook02_guestbook";
	private static final String SELECT_GUESTBOOK_SQL = "select * from guestbook02_guestbook where id=?";
	private static final String SAVE_GUESTBOOKS_SQL = "insert into guestbook02_guestbook(id,name,email,phone,title,content,time) values(gb_seq.nextval,?,?,?,?,?,?)";
	private static final String UPDATE_GUESTBOOKS_SQL = "update guestbook02_guestbook set name=?,email=?,phone=?,title=?,content=? where id=?";
	private static final String DELETE_GUESTBOOKS_SQL = "delete from guestbook02_guestbook where id=?";
	// 也可以将这些常量写在配制文件中（properties）
	OracleUtil db;

	public GuestBookDAOJdbc() {
		db = new OracleUtil("java:/comp/env/jdbc/ds_mysql");
		db.init();
	}

	public boolean delete(Integer id) {
		String params[] = { id.toString() };
		int result = db.update(DELETE_GUESTBOOKS_SQL, params);
		return (result == 1);
	}

	public GuestBook getGuestBook(Integer id) {
		String params[] = { id.toString() };
		List list = (List) db.query(SELECT_GUESTBOOK_SQL, params,
				new BeanListHandler(GuestBook.class));
		return (GuestBook) list.get(0);
	}

	public List getGuestBook() {
		return (List) db.query(SELECT_GUESTBOOKS_SQL, null,
				new BeanListHandler(GuestBook.class));
	}

	public boolean save(GuestBook gb) {
		String params[] = { gb.getName(), gb.getEmail(), gb.getPhone(),
				gb.getTitle(), gb.getContent(), gb.getTime() };
		int result = db.update(UPDATE_GUESTBOOKS_SQL, params);
		return (result == 1);
	}

	public boolean update(GuestBook gb) {
		String params[] = { gb.getName(), gb.getEmail(), gb.getPhone(),
				gb.getTitle(), gb.getContent(), gb.getId().toString() };
		int result = db.update(UPDATE_GUESTBOOKS_SQL, params);
		return (result == 1);
	}

	public Pagination getGuestBookByPage(int pageSize, int pageNumber) {
		Pagination p = new OraclePagination(this.SELECT_GUESTBOOKS_SQL, pageSize, pageNumber);
		return p;
	}

}
